#include <iostream>
#include "Thread.hpp"
#include <vector>

using namespace ThreadModule;

#define NUM 4

// 锁本身是全局的，锁也是共享资源
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int ticketnum = 10000;  // 共享资源

void Ticket()
{
    while(true)
    {
        pthread_mutex_lock(&lock);      // 加锁
        if(ticketnum > 0)
        {
            usleep(1000);
            // 1. 抢票
            printf("get a new ticket, id : %d\n", ticketnum--);

            // 2. 入库模拟
            // usleep(1000);
            pthread_mutex_unlock(&lock);
        }
        else 
        {
            pthread_mutex_unlock(&lock);
            break;
        }
    }
}

int main()
{
    // 1.构建线程对象
    std::vector<Thread> threads;
    for (int i = 0; i < NUM; i++)
    {
        threads.emplace_back(Ticket);
    }

    // 2.启动线程
    for (auto &thread : threads)
    {
        thread.Start();
    }

    // 3. 等待线程
    for (auto &thread : threads)
    {
        thread.Join();
    }

    return 0;
}